package com.xuesinuo.ots.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;

import javax.imageio.ImageIO;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

public class CaptchUtil {
    private static DefaultKaptcha kaptcha;

    static {
        Properties properties = new Properties();
        // 验证码图片宽度
        properties.setProperty("kaptcha.image.width", "150");
        // 验证码图片高度
        properties.setProperty("kaptcha.image.height", "50");
        // 干扰线颜色
        properties.setProperty("kaptcha.noise.color", "200,200,200");
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        kaptcha.setConfig(new Config(properties));
        CaptchUtil.kaptcha = kaptcha;
    }

    /** 获取一个验证码的png图 */
    public static byte[] pngCaptch(String code) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImageIO.write(kaptcha.createImage(code), "png", outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
